package com.ruoyi.livedemo.service;

import com.ruoyi.livedemo.dto.LifeRecordRequest;
import com.ruoyi.livedemo.dto.PagedResult;
import com.ruoyi.livedemo.entity.LifeRecord;
import com.ruoyi.livedemo.mapper.LifeRecordMapper;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
public class LifeRecordService {

    private final LifeRecordMapper lifeRecordMapper;

    public PagedResult<LifeRecord> list(Long userId, int page, int size) {
        int offset = Math.max(page, 0) * size;
        List<LifeRecord> records = lifeRecordMapper.findPage(userId, offset, size);
        long total = lifeRecordMapper.countByUser(userId);
        return new PagedResult<>(total, records);
    }

    @Transactional
    public LifeRecord create(Long userId, LifeRecordRequest request) {
        LifeRecord record = new LifeRecord();
        record.setUserId(userId);
        record.setRecordDate(request.getRecordDate());
        record.setTitle(request.getTitle());
        record.setLocation(request.getLocation());
        record.setWeather(request.getWeather());
        record.setMood(request.getMood());
        record.setDescription(request.getDescription());
        record.setCoverPath(request.getCoverPath());
        record.setAttachmentId(request.getAttachmentId());
        lifeRecordMapper.insert(record);
        return record;
    }

    @Transactional
    public LifeRecord update(Long userId, Long id, LifeRecordRequest request) {
        LifeRecord record = new LifeRecord();
        record.setId(id);
        record.setUserId(userId);
        record.setRecordDate(request.getRecordDate());
        record.setTitle(request.getTitle());
        record.setLocation(request.getLocation());
        record.setWeather(request.getWeather());
        record.setMood(request.getMood());
        record.setDescription(request.getDescription());
        record.setCoverPath(request.getCoverPath());
        record.setAttachmentId(request.getAttachmentId());
        int rows = lifeRecordMapper.update(record);
        if (rows == 0) {
            throw new IllegalArgumentException("未找到生活记录");
        }
        return record;
    }

    @Transactional
    public void delete(Long userId, Long id) {
        lifeRecordMapper.delete(id, userId);
    }
}